package com.zlx.store.user.interceptor;


import com.zlx.store.common.annotation.SecurityAnno;
import com.zlx.store.common.constant.SecurityConstant;
import com.zlx.store.common.exception.IllegalUserException;
import com.zlx.store.domain.entity.vo.TokenVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Objects;

@Slf4j
@Component
public class SecurityInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 权限拦截器，使用redis和自定义注解进行拦截
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handler1 = (HandlerMethod) handler;
        Method method = handler1.getMethod();
        SecurityAnno declaredAnnotation = method.getDeclaredAnnotation(SecurityAnno.class);
        String token = request.getHeader("token");
        TokenVO tokenVO = (TokenVO) redisTemplate.opsForValue().get(token);
        if (Objects.nonNull(declaredAnnotation)) {
            SecurityConstant[] securityConstants = declaredAnnotation.roleName();
            SecurityConstant securityConstant = securityConstants[0];
            if (securityConstant.getCode() == (tokenVO.getUserRole()))
                return true;
        } else throw new IllegalUserException("权限不足");
        return false;
    }
}
